<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\book\model;

use manniu\model\Base;

use think\Cache;

class BookBookcases extends Base
{
    // 最后一次阅读章节id - 数据自动完成
    protected $insert = ['lrc_id' => 0];

    /**
     * 根据用户id更新书架缓存
     * @access public
     * @param int $uid 用户ID
     * @return mixed
     */
    public static function updateBookcaseCacheByUid($uid = 0)
    {
        Cache::rm('bookcases_uid_' . $uid);
        $uid = (int)$uid;
        if ($uid) {
            $list = self::field('book_id,lrc_id')->where('uid', $uid)->select();
            if ($list) {
                $list = collection($list)->toArray();
                $data = [];
                foreach ($list as $bookcase_key => $bookcase_value) {
                    $data[$bookcase_value['book_id']] = $bookcase_value;
                }
                Cache::set('bookcases_uid_' . $uid, $data);
            }
        }
    }

    /**
     * 检查图书是否在书架
     * @param $uid
     * @param $book_id
     * @return bool
     */
    public static function bookcaseExists($uid, $book_id)
    {
        if (self::where(['uid' => $uid, 'book_id' => $book_id])->count()) {
            return true;
        }
        return false;
    }

    /**
     * 保存用户阅读记录
     * @param $uid
     * @param $book_id
     * @param $chapter_id
     */
    public static function saveReadingRecord($uid, $book_id, $chapter_id)
    {
        $bookcase = self::where(['uid' => $uid, 'book_id' => $book_id])->find();
        if ($bookcase && $bookcase->lrc_id != $chapter_id) {
            $bookcase->lrc_id = $chapter_id;
            $bookcase->save();
        }
    }
}